# log flow server
# read log files and send it to client by network

import sys
import os
import time
from watchdog.observers import Observer
from watchdog.events import LoggingEventHandler

class FileModifyReader(LoggingEventHandler):
    def __init__(self, path, receiver):
        self.file_map = {}
        self.path = path['path']
        self.file_list = path['file_list']
        self.receiver = receiver

    def run(self):
        observer = Observer()
        observer.schedule(self, self.path, recursive=self.recursive)
        observer.start()
        return observer

    def on_modified(self, event):
        # print(event)
        self.modified_reader(event)

    def modified_reader(self, event):
        file_name = event.src_path[len(self.path):]
        isfile = os.path.isfile(event.src_path)
        if not isfile or file_name not in self.file_list:
            return

        fp = self.file_map.get(event.src_path)
        if not fp:
            fp = open(event.src_path, "rb")
            self.file_map[event.src_path] = fp

        #print("[{time}] Change: {src_path}".format(time=time.asctime(), src_path=event.src_path))
        self.write_to_queue(fp)

    def write_to_queue(self, fp):
        self.receiver.extend(fp.readlines())


if __name__ == "__main__":
    import logging
    logging.basicConfig(level=logging.INFO,
                        format='%(asctime)s - %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S')
    path = sys.argv[1] if len(sys.argv) > 1 else '.'
    buf = []
    file_modify_event = FileModifyReader(path, buf)
    file_modify_event.run()
